//
//  LoginVerifyViewController.m
//  us
//
//  Created by karry on 2025/3/30.
//

#import "LoginVerifyViewController.h"
#import "CharacterViewController.h"
#import "LoginBackgroundView.h"
#import "CodeView.h"
#import "SceneDelegate.h"
#import <JPUSHService.h>

@interface LoginVerifyViewController ()

@property (nonatomic, strong) LoginBackgroundView *backgroundView;

@property (nonatomic, strong) CodeView *codeView;

@property (nonatomic, strong) MOSendCodeButton *codeBtn;

@property (nonatomic, strong) UIButton *nextStepBtn;

@property (nonatomic, strong) NSString *code;
@end

@implementation LoginVerifyViewController


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.codeView startEdit];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [self.codeBtn jk_stopTimer];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 

    self.backgroundView = [LoginBackgroundView jk_loadInstanceFromNib];
    self.backgroundView.lab1.text = @"输入验证码";
    [self.backgroundView.lottieWrapper playAnimation];

    
    NSString *text = [NSString stringWithFormat:@"验证码已发送至%@",self.phoneNum];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    NSRange phoneRange = [text rangeOfString:self.phoneNum];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor jk_colorWithHex:0x212121] range:phoneRange];
    self.backgroundView.lab2.attributedText = attributedString;
    [self.view addSubview:self.backgroundView];
    
    @weakify(self);
    RAC(self.nextStepBtn, enabled) = [RACObserve(self, code) map:^id _Nullable(NSString * _Nullable text) {
        @strongify(self);
        if (text.length == 4) {
            [self nextStepAction];
        }
        return @(text.length == 4);
    }];
 
    self.codeView = [[CodeView alloc]initWithFrame:CGRectMake(32, 138, ScreenWidth - 64, 64) codeNumber:4 style:CodeStyle_border labelFont:43 labelTextColor:UIColor.titleColor mainColor:UIColor.brightBorderColor normalColor:UIColor.borderColor selectCodeBlock:^(NSString * code) {
        @strongify(self);
        self.code = code;
    }];
    
    [self.backgroundView addSubview:self.codeView];

    [self.backgroundView addSubview:self.codeBtn];
 
    [self.codeBtn jk_startTime:59 title:@"重新获取" waitTittle:@"重新获取 "];

    [self.view addSubview:self.nextStepBtn];
  
    [self initLayout];
    
    [self setupKeyboardObservers];

    [self.view layoutIfNeeded];
 
}


- (void)setupKeyboardObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWillHide:)
//                                                 name:UIKeyboardWillHideNotification
//                                               object:nil];
}

// 修改键盘显示处理方法
- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGRect keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    [self.nextStepBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.backgroundView.mas_bottom).offset(-keyboardFrame.size.height);
    }];

    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)initLayout{
  
    [self.backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
    }];
    
    [self.codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.codeView.mas_bottom).offset(15);
        make.centerX.equalTo(self.backgroundView);
    }];
    
    [self.nextStepBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(32);
        make.right.equalTo(self.view.mas_right).offset(-32);
        make.height.mas_equalTo(56);
        make.bottom.equalTo(self.backgroundView.mas_bottom).offset(-168 - kSafeAreaBottomHeight);
    }];

    
}

 
 
 
- (UIButton *)nextStepBtn {
    if (_nextStepBtn == nil) {
        _nextStepBtn = [UIButton us_fillButtonWithTitle:@"下一步"];
        _nextStepBtn.layer.cornerRadius = 14;
        [_nextStepBtn addTarget:self action:@selector(nextStepAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextStepBtn;
}

- (MOSendCodeButton *)codeBtn {
    if (_codeBtn == nil) {
        _codeBtn = [MOSendCodeButton buttonWithType:UIButtonTypeCustom];
        [_codeBtn setTitle:@"发送验证码" forState:0];
        [_codeBtn addTarget:self action:@selector(sendCode:) forControlEvents:UIControlEventTouchUpInside];
        [_codeBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [_codeBtn setTitleColor:UIColor.systemBlueColor forState:0];
        [_codeBtn setTitleColor:[UIColor jk_colorWithHex:0x212121 andAlpha:0.4] forState:UIControlStateDisabled];
    }
    return _codeBtn;
}

- (void)nextStepAction {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"1" forKey:@"systemType"];
    [params setValue:self.phoneNum?:@"" forKey:@"phoneNumber"];
    [params setValue:self.code?:@"" forKey:@"verificationCode"];
    [[EMNetWork shareManager]em_post:API_Login params:params hud:@"" showError:YES success:^(EMApiModel *api) {
        if (api.success == NO) {
            
            [self.codeView clean];
            return;
        }
 
 
        USUser *user = [USUser mj_objectWithKeyValues:api.data];
        if (api.data[@"user"]) {
            user = [USUser mj_objectWithKeyValues:api.data[@"user"]];        
        }
        [USUser saveUser:user];

        
        [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
            if (registrationID.length > 0) {
                ///更新 registrationID
            
                [[EMNetWork shareManager] em_post:API_EditUser
                                           params:@{@"registrationId":registrationID}
                                              hud:nil
                                       showError:NO
                                          success:^(EMApiModel *api) {
           
                } fail:^{
                     
                    
                }];
            }
        }];
        
        
        [[EMClient sharedClient] loginWithUsername:user.imUserName token:user.imToken completion:^(NSString * _Nonnull aUsername, EMError * _Nullable aError) {
            if (aError) {
                NSLog(@"环信登录失败 ---- %li,%@",aError.code,aError);

            }else {
                NSLog(@"环信登录成功");
            }
        }];

        [self.view endEditing:YES];
        
        if (user.isNew) {
            CharacterViewController *vc = [[CharacterViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }else{

            UIWindowScene *scene = (UIWindowScene *)[UIApplication sharedApplication].connectedScenes.allObjects.firstObject;
            
            SceneDelegate *sceneDelegate = (SceneDelegate *)scene.delegate;
            
            [sceneDelegate switchToMainInterface];
        }
        
     
    } fail:^{
        
    }];
 

  
}

- (void)sendCode:(MOSendCodeButton *)sender{
    [USFeedbackTool impactLight];
        
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"1" forKey:@"systemType"];
    [params setValue:self.phoneNum?:@"" forKey:@"phoneNumber"];
    [[EMNetWork shareManager]em_post:API_Verification params:params hud:@"" showError:YES success:^(EMApiModel *api) {
        if (api.success == NO) {
            [self.view endEditing:YES];
            return;
        }
        [self.view makeToast:@"验证码已发送"];
        [sender jk_startTime:59 title:@"重新获取" waitTittle:@"重新获取 "];
        [self.codeView startEdit];
        

    } fail:^{
        
    }];
 
    
}

- (void)dealloc {
    NSLog(@"------ dealloc");
}
@end
